<template>
    <section>
        <!--工具条-->

        <div class="section-content clearfix">
            <el-col :span="24" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="filters">
                    <el-form-item>
                        <el-input v-model="filters.name" placeholder="告警规则名" @keyup.enter.native="getUsers()" :disabled="filters.alarmTriggerGroupId"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="filters.level" placeholder="请选择告警等级" @change="getUsers()" :disabled="filters.alarmTriggerGroupId">
                            <el-option label="默认" value=" "></el-option>
                            <el-option v-for="item in alaem_grade" :label="item.remark" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="filters.alarmTypeId" placeholder="请选择告警类型" @change="getUsers()" :disabled="filters.alarmTriggerGroupId">
                            <el-option label="默认" value=" "></el-option>
                            <el-option v-for="item in alaem_type" :label="item.name" :value="item.id"></el-option>
                            <!-- <el-option label="类型2" value="2"></el-option> -->
                        </el-select>
                    </el-form-item>
                    <el-form-item  >
                            <el-select v-model="filters.deviceTypeId" placeholder="请选择设备类型" @change="getUsers()" :disabled="filters.alarmTriggerGroupId">
                                    <el-option label="默认" ></el-option>
                                <el-option v-for="item in typelist" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item  >
                                <el-select v-model="filters.alarmTriggerGroupId" placeholder="请选择告警组" @change="groupget()">
                                        <el-option label="默认" ></el-option>
                                    <el-option v-for="item in grouplist" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        <el-form-item  >
                            <el-select v-model="filters.deviceDataRecipeId" placeholder="数据模板" @change="getUsers()" :disabled="filters.alarmTriggerGroupId">
                                    <el-option label="默认" value=''></el-option>
                                <el-option v-for="item in deviceDataRecipe" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item  >
                            <el-select v-model="filters.deviceDataRecipeBodyId" placeholder="数据点" @change="getUsers()" :disabled="filters.alarmTriggerGroupId">
                                    <el-option label="默认" value=''></el-option>
                                <el-option v-for="item in deviceDataRecipeBody" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    <el-form-item>
                        <el-button :type="buttonColor" v-on:click="getUsers">查询</el-button>
                    </el-form-item>
                    <el-form-item v-if="menubt.indexOf('alarm_trigger/post')>-1">

                            <el-button :type="buttonColor" @click="typepost()">新增</el-button>
                    </el-form-item>
                    <!-- <el-form-item v-if="menubt.indexOf('alarm_trigger/post')>-1">
                            <el-button :type="buttonColor" @click="tableToExcel()">模板下载</el-button>
                    </el-form-item>
                    <el-form-item v-if="menubt.indexOf('alarm_trigger/post')>-1">
                            <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" ref="upload"
                            accept=".xls,.xlsx" :on-change="upload" :show-file-list="false" :auto-upload="false" style="display: inline;">
                            <el-button size="small" :type="buttonColor">批量导入</el-button>
                        </el-upload>
                    </el-form-item> -->
                </el-form>
            </el-col>

            <!--列表-->
            <el-table :data="query" highlight-current-row v-loading="listLoading" :header-row-style="{backgroundColor: titleColor}" @selection-change="selsChange" style="width: 100%;">
                <el-table-column type="selection">
                </el-table-column>
                <el-table-column type="index" label="序号"  width="80":index="indexMethod">
                </el-table-column>
                <el-table-column prop="name" label="告警规则名">
                </el-table-column>
                <el-table-column prop="customContent" label="告警触发推送内容">
                </el-table-column>
                <el-table-column prop="customContentNormal" label="告警解除推送内容">
                </el-table-column>
                <el-table-column prop="alarmTypeId" label="告警分类" :formatter="formatType">
                    </el-table-column>
                <el-table-column prop="levelText" label="告警等级">
                </el-table-column>
                <el-table-column  label="告警组">
                        <template scope="scope">
                            <div v-for="item in scope.row.alarmTriggerGroupList" v-if="item.type==2">{{item.name}}</div>
                            
                      
                        </template>
                </el-table-column>
                <!-- <el-table-column prop="createTime" label="创建时间">
                </el-table-column>
                <el-table-column prop="updateTime" label="更新时间">
                </el-table-column> -->
                <el-table-column label="当前状态">
                    <template scope="scope">

                        <span v-if="scope.row.status==0" 
                            >已停用</span>
                        <span v-if="scope.row.status==1" 
                            >已启用</span>
                    </template>
                </el-table-column>
                <el-table-column label="告警规则设置" v-if="menubt.indexOf('alarm_trigger/open_or_close')>-1">
                    <template scope="scope">

                        <el-button v-if="scope.row.status==0" title="点击启用" size="small" @click="stateput( scope.row)" :type="buttonColor"
                            plain>启用</el-button>
                        <el-button v-if="scope.row.status==1" title="点击停用" size="small" type="small" @click="stateput( scope.row)"
                            plain>停用</el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="告警屏蔽配置" v-if="menubt.indexOf('alarm_trigger/put_mask')>-1">
                    <template scope="scope">
                        <i @click="maskFormEdit(scope.$index, scope.row)" title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i>

                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template scope="scope">
                        <i v-if="menubt.indexOf('alarm_trigger/put')>-1" @click="handleEdit(scope.$index, scope.row)" title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i>
                        <i v-if="menubt.indexOf('alarm_trigger/delete')>-1" @click="handleDel(scope.$index, scope.row)" icon="el-icon-delete" circle title="删除" class="pb-icon icon-delete"></i>
                    </template>
                </el-table-column>
            </el-table>

            <!--工具条-->
            <el-col :span="24" class="toolbar">
                <el-button v-if="menubt.indexOf('alarm_trigger/delete')>-1" type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
                <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total"
                    style="float:right;">
                </el-pagination>
            </el-col>
        </div>
        <el-dialog title="告警屏蔽设置" v-show="maskFormVisible" v-model="maskFormVisible" :custom-class="dialogTitleColor" @close="maskFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="editmask" label-width="100px" ref="editForm">
                    <el-form-item>
                        <el-date-picker v-model="value4" @change="second1()" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker>
                        <el-radio-group  v-model="maskStatus" @change="statemaskput()"  >
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="0">停用</el-radio>
                          </el-radio-group>
                    </el-form-item>
                    <!-- <el-form-item label="告警组">
                            <el-transfer v-model="alarmUserLists" :data="userlists" style="margin-left:30px;padding-bottom:20px;"></el-transfer>
                        </el-form-item> -->
                    <el-form-item v-for="item in editmask.maskWithout" :label="item.name">
                        <!-- <el-transfer v-model="alarmUserList" :data="userlist" style="margin-left:30px;padding-bottom:20px;"></el-transfer> -->
                        <el-checkbox-group v-model="item.list" class="triggers-checkbox">
                            <el-checkbox v-for="(items,indexs) in masklist" :label="items" name="indexs"></el-checkbox>

                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="maskFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="maskSubmit" :loading="editLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" :custom-class="dialogTitleColor" @close="editFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="editForm" label-width="140px" :rules="editFormRules" ref="editForms">
                    <el-form-item label="告警点名称" class="grade" prop="name">
                        <el-input v-model="editForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="告警类型">
                        <el-select v-model="editForm.alarmTypeId" placeholder="请选择告警类型" class="grade">
                            <el-option v-for="item in alaem_type" :label="item.name" :value="item.id"></el-option>
                            <!-- <el-option label="类型2" value="2"></el-option> -->
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据模板ID" class="grade" prop="deviceDataRecipeId">
                        <el-select v-model="editForm.deviceDataRecipeId" @change="second()" placeholder="请选择数据模板ID">
                            <el-option v-for="item in deviceDataRecipe" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据模板数据点ID" class="grade" prop="deviceDataRecipeBodyId">
                        <el-select v-model="editForm.deviceDataRecipeBodyId" placeholder="请选择数据模板数据点ID">
                            <el-option v-for="item in deviceDataRecipeBody" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="告警等级" class="grade">
                        <el-select v-model="editForm.level" placeholder="请选择告警等级">
                            <el-option v-for="item in alaem_grade" :label="item.remark" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备类型" class="grade" prop="deviceTypeId">
                            <el-select v-model="editForm.deviceTypeId" placeholder="请选择设备类型">
                                <el-option v-for="item in typelist" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    <!-- <el-form-item label="数据点" class="grade">
                        <el-input v-model="editForm.register"></el-input>
                    </el-form-item> -->
                
                    <el-form-item label="触发条件" class="grade" prop="triggerCondition">
                            <el-select v-model="editForm.triggerCondition" @change="Condition()">
                                <el-option v-for="item in unitlist" :label="item.remark" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="触发A值" class="grade" prop="inputMin" >
                            <el-input type="number" v-model="editForm.inputMin" :disabled="editFormRules.inputMin.length==0"></el-input>
                        </el-form-item>
                        <el-form-item type="number" label="触发B值" class="grade" prop="inputMax">
                            <el-input v-model="editForm.inputMax" :disabled="editFormRules.inputMax.length==0"></el-input>
                        </el-form-item>
                    <el-form-item label="告警方式" class="grade">
                        <el-radio-group v-model="editForm.alarmMode">
                            <el-radio label="1">微信</el-radio>
                            <el-radio label="2">短信</el-radio>
                            <!-- <el-radio label="3">邮件</el-radio> -->
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否存储数据" class="grade">
                        <el-radio-group v-model="editForm.isSave">
                            <el-radio label="0">否</el-radio>
                            <el-radio label="1">是</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <!-- <el-form-item label="启用状态" class="grade">
                        <el-radio-group v-model="editForm.status">
                            <el-radio label="0" value="0">不启用</el-radio>
                            <el-radio label="1" value="1">启用</el-radio>
                        </el-radio-group>
                    </el-form-item> -->
                    <el-form-item label="触发告警推送内容" prop="customContent">
                        <el-input type="textarea" v-model="editForm.customContent"></el-input>
                    </el-form-item>
                    <el-form-item label="告警解除推送内容" prop="customContentNormal">
                        <el-input type="textarea" v-model="editForm.customContentNormal"></el-input>
                    </el-form-item>
                    <el-form-item label="备注"  >
                        <el-input type="textarea" v-model="editForm.remark"></el-input>
                    </el-form-item>

                    <!-- <el-form-item label="告警组">
                        <el-transfer v-model="alarmUserLists" :data="userlists" style="margin-left:30px;padding-bottom:20px;"></el-transfer>
                    </el-form-item> -->
                    <!-- </el-form-item> -->
                    <el-form-item label="告警人/组">
                        <el-transfer :titles="['可选', '已选']" :button-texts="['到左边', '到右边']"  v-model="alarmUserList" :data="userlist" style="margin-left:30px;padding-bottom:20px;"></el-transfer>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="editFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="editSubmit" :loading="editLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>

        <!--新增界面-->

    </section>
</template>

<script>
    // import util from './../common/js/util'
    //import NProgress from 'nprogress'
    import qs from 'qs';
    import XLSX from 'xlsx'
    import {
        alarm_trigger_query,
        alarm_trigger_put,
        alarm_trigger_post,
        alarm_group_query,
        alarms_query_user,
        alarm_trigger_get,
        alarm_trigger_delete,
        alarms_put_user,
        dict_query,
        alarm_type_query,
        device_data_recipe_query,
        device_data_recipe_list_body,
        alarm_trigger_open_or_close_mask,
        alarm_trigger_open_or_close,
        alarm_trigger_get_mask,
        alarm_trigger_put_mask,
        device_type_query
    } from '../../api/api';

    export default {

        data() {

            const generateData = _ => {
                const data = [];
                let para = {};
                //NProgress.start();
                alarms_query_user(para).then((res) => {
                     this.begCode(res.code,res.message);
                    // this.total = res.data.totalCount;
                    if (res.code == 0) {
                        for (let i in res.data.list) {
                            data.push({
                                type: 1,
                                sid: res.data.list[i].id,
                                label: res.data.list[i].name + "(告警人)"
                            });
                        }
                    } else {
                        this.$router.push({
                            path: '/login'
                        });
                    }
                    //NProgress.done();
                });
                alarm_group_query(para).then((res) => {
                     this.begCode(res.code,res.message);
                    // this.total = res.data.totalCount;
                    if (res.code == 0) {
                        
                        this.grouplist = res.data.list;
                        for (let i in res.data.list) {
                            data.push({
                                type: 2,
                                sid: res.data.list[i].id,
                                label: res.data.list[i].name + "(告警组)"
                            });
                        }
                    } else {
                        this.$router.push({
                            path: '/login'
                        });
                    }
                    //NProgress.done();
                });
             
                return data;
            };
            return {
                grouplist:[],
                maskStatus:'',
                value4: [],
                alarmUserList: [], //告警组ID
                alarmUserLists: [], //告警人ID
                alarmTypeValue: '',
                userlist: generateData(),
                // userlists: generateDatas(),
                unitlist: '',
                alaem_type: '',
                alaem_grade: '',
                filters: {
                    name: '',
                    level: '',
                    alarmTypeId: '',
                    deviceTypeId:sessionStorage.getItem('triggerstype'),
                    alarmTriggerGroupId:null,
                    deviceDataRecipeBodyId:sessionStorage.getItem('deviceDataRecipeBodyId'),
                    // deviceDataRecipeBodyId:'',
                    // deviceDataRecipeId:''
                    deviceDataRecipeId:sessionStorage.getItem('deviceDataRecipeId')
                },
                query: [],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [], //列表选中列
                masklist: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16',
                    '17', '18', '19', '20', '21', '22', '23'
                ],
                editmask: {
                    alarmTriggerId: '',
                    maskStartTime: '',
                    maskEndTime: '',
                    maskWithout: [{
                            name: '星期一',
                            list: ['']
                        },
                        {
                            name: '星期二',
                            list: []
                        }, {
                            name: '星期三',
                            list: []
                        }, {
                            name: '星期四',
                            list: []
                        }, {
                            name: '星期五',
                            list: []
                        }, {
                            name: '星期六',
                            list: []
                        }, {
                            name: '星期日',
                            list: []
                        },
                    ]
                },
                maskFormVisible: false,
                editFormVisible: false, //编辑界面是否显示
                editLoading: false,
                editFormRules: {
                   
                    name: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    },{ min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                    alarmTypeId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    deviceDataRecipeId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    deviceDataRecipeBodyId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    level: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    deviceTypeId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    register: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    triggerCondition: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    inputMin: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    inputMax: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    alarmMode: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    isSave: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    status: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    customContent: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    customContentNormal: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    remark: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],


              
                },
                deviceDataRecipe: '',
                deviceDataRecipeBody: '',
                
                typelist:'',
                //编辑界面数据
                editForm: {
                    deviceTypeId:'',
                    alarmTypeId: '',
                    name: '',
                    deviceDataRecipeId: '',
                    deviceDataRecipeBodyId: '',
                    level: '',
                    register: '',
                    triggerCondition: '',
                    inputMin: '',
                    inputMax: '',
                    alarmMode: '',
                    isSave: '',
                    status: '',
                    customContent: '',
                    customContentNormal: '',
                    remark: '',
                    alarmTriggerGroupList: [],
                    alarmUserList: [],
                    alarmUserLists: []
                },


            }


        },
        computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
        methods: {
            upload(file, fileList) {
                console.log("file", file);
                console.log("fileList", fileList);
                let files = {
                    0: file.raw
                }
                this.readExcel1(files);
            },
            readExcel1(files) { //表格导入
                var that = this;
                console.log(files);
                if (files.length <= 0) { //如果没有文件名
                    return false;
                } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
                    this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
                    return false;
                }

                const fileReader = new FileReader();
                fileReader.onload = (ev) => {
                    console.log('ev=====================>',ev)
                    try {
                        const data = ev.target.result;
                        const workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        const wsname = workbook.SheetNames[0]; //取第一张表
                        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
                        console.log(ws)
                        for(let i in ws){   
                            let deviceTypeId = this.typelist.find(item =>{
                                return item.name == ws[i].设备类型
                            })
                            let alarmTypeId = this.alaem_type.find(item => {
                                return item.name == ws[i].告警类型
                            })
                            let deviceDataRecipeId = this.deviceDataRecipe.find(item => {
                                return item.name == ws[i].数据模板ID
                            })
                            // this.editForm.deviceDataRecipeId = deviceDataRecipeId.id
                            let para = {
                                deviceDataRecipeId:deviceDataRecipeId.id
                            }
                            let _this = this
                            //1,new
                            let oAjax = new XMLHttpRequest();
                            //2,open
                            oAjax.open('POST', '/api/iot/device_data_recipe/list_body', false);
                            //3,setHeader,get请求不需要
                            oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                            oAjax.setRequestHeader("token",JSON.parse(localStorage.getItem('key')));//获取到token
                            oAjax.setRequestHeader("Accept",'application/json,text/plain');
                            //4，定义返回触发的函数，定义在send之前，不然同步请求就出问题
                            oAjax.onreadystatechange = function() {
                                //6,通过状态确认完成
                                if (oAjax.readyState == 4 && oAjax.status == 200) {
                                    //7,获取返回值，解析json格式字符串为对象
                                    // var res = JSON.parse(oAjax.responseText);
                                    // console.log(JSON.parse(oAjax.responseText))
                                    if(JSON.parse(oAjax.responseText).code == 0){
                                        _this.deviceDataRecipeBody = JSON.parse(oAjax.responseText).data.list
                                    }    
                                } else {
                                    console.log(oAjax);
                                }
                            };
                            //，5发送，发送内容格式"a=1&b=2"，而不是json
                            oAjax.send(qs.stringify(para));
                            console.log(_this.deviceDataRecipeBody)

                            let deviceDataRecipeBodyId = _this.deviceDataRecipeBody.find(item => {
                                return item.name == ws[i].数据模板数据点ID
                            })
                            let level = _this.alaem_grade.find(item => {
                                return item.remark == ws[i].告警等级
                            })
                            let triggerCondition = _this.unitlist.find(item => {
                                return item.remark == ws[i].触发条件
                            })
                            
                            let addForm = { 
                                    deviceTypeId: deviceTypeId.id, //设备类型
                                    alarmTypeId: alarmTypeId.id, //告警类型
                                    name: ws[i].告警点名称,
                                    deviceDataRecipeId: deviceDataRecipeId.id, //数据模板ID
                                    deviceDataRecipeBodyId: deviceDataRecipeBodyId.id,  //数据模板数据点ID
                                    level: level.value, //告警等级
                                    triggerCondition: triggerCondition.value,
                                    inputMin: ws[i].触发A值,
                                    inputMax: ws[i].触发B值,
                                    alarmMode: '1',
                                    isSave: '0',
                                    status: '0',
                                    customContent: ws[i].告警触发推送内容,
                                    customContentNormal: ws[i].告警解除推送内容,
                                    remark: ws[i].备注,
                                }
                            console.log(addForm)
                            alarm_trigger_post(addForm).then((res) => {
                                this.begCode(res.code,res.message);
                                if (res.code == 0) {
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                }

                            });

                        }
                        
                        //重写数据
                        try {

                        } catch (err) {
                            console.log(err)
                        }

                        this.$refs.upload.value = '';

                    } catch (e) {

                        return false;
                    }
                };
                fileReader.readAsBinaryString(files[0]);
                this.$router.push({
                    path: "/alarms/triggers"
                });
            },

            tableToExcel(){
                 window.location.href = "http://" + location.host + "/告警分类模板.xls"
                // //列标题，逗号隔开，每一个逗号就是隔开一个单元格
                // let str = `告警点名称,告警类型,设备类型,数据模板ID,数据模板数据点ID,告警等级,触发条件,触发A值,触发B值,告警触发推送内容,告警解除推送内容,备注\n`;
                // //增加\t为了不让表格显示科学计数法或者其他格式
                // // for(let i = 0 ; i < jsonData.length ; i++ ){
                // //     for(let item in jsonData[i]){
                // //         str+=`${jsonData[i][item] + '\t'},`;     
                // //     }
                // //     str+='\n';
                // // }
                // //encodeURIComponent解决中文乱码
                // let uri = 'data:text/xls;charset=utf-8,\ufeff' + encodeURIComponent(str);
                // //通过创建a标签实现
                // let link = document.createElement("a");
                // link.href = uri;
                // //对下载的文件命名
                // link.download =  "告警分类模板.xls";
                // document.body.appendChild(link);
                // link.click();
                // document.body.removeChild(link);               
            },
            Condition() {
                console.log(this.editForm.triggerCondition);
                if (this.editForm.triggerCondition == 0 || this.editForm.triggerCondition == 4) {
                    this.editFormRules.inputMin = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                    this.editFormRules.inputMax=[];
                } else if (this.editForm.triggerCondition == 1) {
                    this.editFormRules.inputMin=[];
                    this.editFormRules.inputMax = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                } else if (this.editForm.triggerCondition == 2 || this.editForm.triggerCondition == 3) {
                    this.editFormRules.inputMax = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                    this.editFormRules.inputMin = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                }
            },
            groupget(){
                this.filters= {
                    name: '',
                    level: '',
                    alarmTypeId: '',
                    deviceTypeId:'',
                    alarmTriggerGroupId:this.filters.alarmTriggerGroupId
                }
                this.getUsers();
            },
            indexMethod(index) {
                let num = (this.page - 1) * 10 + index + 1;
                return num;
            },
            typepost(){
               if(this.filters.deviceTypeId){
                localStorage.setItem('typepost',this.filters.deviceTypeId)
               }
        this.$router.push({ path: "/alarms/triggers/post" });
            },
            getdata(date) {
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                m = m < 10 ? ('0' + m) : m;
                var d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                var h = date.getHours();
                h = h < 10 ? ('0' + h) : h;
                var minute = date.getMinutes();
                minute = minute < 10 ? ('0' + minute) : minute;
                var second = date.getSeconds();
                second = second < 10 ? ('0' + second) : second;
                return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;

            },
            second1() {

                this.editmask.maskStartTime = this.getdata(this.value4[0]);
                this.editmask.maskEndTime = this.getdata(this.value4[1]);
            },
            statemaskput() {
                let para = {
                    id: this.editmask.alarmTriggerId
                }
                alarm_trigger_open_or_close_mask(para).then((res) => {

                     this.begCode(res.code,res.message);
                    if (res.code == 0) {

                        //NProgress.done();
                        this.$message({
                            message: '状态修改成功',
                            type: 'success'
                        });

                        this.getUsers();

                    }
                });


            },
            stateput(s) {
                
                let para = {
                    id: s.alarmTriggerId
                }
                alarm_trigger_open_or_close(para).then((res) => {

                     this.begCode(res.code,res.message);
                    if (res.code == 0) {

                        //NProgress.done();
                        this.$message({
                            message: '状态修改成功',
                            type: 'success'
                        });

                        this.getUsers();

                    }
                });


            },
            second: function () {
                if (this.editForm.deviceDataRecipeId) {
                    let para = {
                        deviceDataRecipeId: this.editForm.deviceDataRecipeId,
                    };
                    device_data_recipe_list_body(para).then((res) => {
                         this.begCode(res.code,res.message);
                        if (res.code == 0) {
                            //NProgress.done();
                            this.deviceDataRecipeBody = res.data.list;
                        }
                    });
                } else {
                    this.deviceDataRecipeBody = {};
                }

            },
            //性别显示转换
            formalevel: function (row, column) {

                return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            },
            formatType(row, column){
                for(let i in this.alaem_type){
                    
                    if(this.alaem_type[i].id==row.alarmTypeId){

                    return this.alaem_type[i].name;
                    }
                }
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            //获取菜单列表
            getUsers() {
               
                let para = {
                    pageNo: this.page,
                    pageSize: 10,
                    name: this.filters.name,
                    level: this.filters.level,
                    alarmTypeId: this.filters.alarmTypeId,
                    deviceTypeId:this.filters.deviceTypeId,
                    alarmTriggerGroupId:this.filters.alarmTriggerGroupId,
                    deviceDataRecipeId:this.filters.deviceDataRecipeId,
                    deviceDataRecipeBodyId:this.filters.deviceDataRecipeBodyId,
                    alarmTriggerId:sessionStorage.getItem('facility_alarmTriggerId')
                };
                this.listLoading = true;
                //NProgress.start();
                
                sessionStorage.removeItem('facility_alarmTriggerId')
                alarm_trigger_query(para).then((res) => {
                     this.begCode(res.code,res.message);
                    this.total = res.data.totalCount;
                    if (res.code == 0) {
                        this.query = res.data.list;
                        console.log(this.query);
                    }
                    this.listLoading = false;
                    //NProgress.done();
                });
                if (this.filters.deviceDataRecipeId) {
                    let para = {
                        deviceDataRecipeId: this.filters.deviceDataRecipeId,
                    };
                    device_data_recipe_list_body(para).then((res) => {
                         this.begCode(res.code,res.message);
                        if (res.code == 0) {
                            //NProgress.done();
                            this.deviceDataRecipeBody = res.data.list;
                        }
                    });
                } else {
                    this.deviceDataRecipeBody = {};
                }
            },
            //删除
            handleDel: function (index, row) {
              
                this.$confirm('确认删除该选项吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        idList: [row.alarmTriggerId]
                    };
                    alarm_trigger_delete(para).then((res) => {
                         this.begCode(res.code,res.message);
                        if (res.code == 0) {

                            this.listLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getUsers();

                        }
                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            maskFormEdit(index, row) {
                this.value4=[];
                this.maskFormVisible = true;
                this.editmask={
                    alarmTriggerId: '',
                    maskStartTime: '',
                    maskEndTime: '',
                    maskWithout: [{
                            name: '星期一',
                            list: ['']
                        },
                        {
                            name: '星期二',
                            list: []
                        }, {
                            name: '星期三',
                            list: []
                        }, {
                            name: '星期四',
                            list: []
                        }, {
                            name: '星期五',
                            list: []
                        }, {
                            name: '星期六',
                            list: []
                        }, {
                            name: '星期日',
                            list: []
                        },
                    ]
                };
                let para = {
                    id: row.alarmTriggerId
                }
                alarm_trigger_get_mask(para).then((res) => {
                    console.log(res)
                     this.begCode(res.code,res.message);
                    // this.total = res.data.totalCount;
                    if (res.code == 0) {
                        for (let i = 0; i < 7; i++) {
                            if (res.data.maskWithout[i + 1]) {
                                this.editmask.maskWithout[i].list = res.data.maskWithout[i + 1].split(',')
                                // this.editmask.maskWithout[i].list=[1]
                                console.log(this.editmask.maskWithout[i].list)
                            } else {
                                // this.editmask.maskWithout[i].list=[];
                            }
                        }

                        this.editmask.alarmTriggerId = res.data.alarmTriggerId;
                        if(res.data.maskEndTime||res.data.maskStartTime){
                           
                        // this.value4=[,]
                          let start1 = new Date(res.data.maskStartTime);
                          let start2 = Date.parse(new Date(res.data.maskEndTime));
                          var time1 = start1.getTime();
                        var time2 = start1.valueOf(); 
                        var time3 = Date.parse(start1);
                        console.log(time1);//1398250549123
                        console.log(time2);//1398250549123
                        console.log(time3);//1398250549000
                        this.editmask.maskStartTime = res.data.maskStartTime;
                        this.editmask.maskEndTime = res.data.maskEndTime;
                        this.value4 = [start1, start2];
                         
                    }
                        this.maskStatus=res.data.maskStatus;

                    }
                });

            },
            handleEdit: function (index, row) {
             
                for(let i in this.userlist){
                    this.userlist[i].key=i;
                }
                this.editFormVisible = true;

                let para = {
                    id: row.alarmTriggerId
                }
                alarm_trigger_get(para).then((res) => {
                     this.begCode(res.code,res.message);
                    // this.total = res.data.totalCount;
                    if (res.code == 0) {

                        this.editForm = Object.assign({}, res.data);
                        this.editForm.isSave = this.editForm.isSave.toString();
                        this.editForm.status = this.editForm.status.toString();
                        this.editForm.level = this.editForm.level.toString();
                        this.alarmUserList = [];
                        this.alarmUserLists = [];
                        this.second();
                        for (let j in this.userlist) {

                            for (let i in res.data.triggerGroupList) {

                                console.log(res.data.triggerGroupList)
                                if (res.data.triggerGroupList[i].type == this.userlist[j].type && res.data.triggerGroupList[
                                        i].alarmTypeValue == this.userlist[j].sid) {

                                    this.alarmUserList.push(j);
                                    console.log(this.alarmUserList)

                                }
                            }

                        }
                        
                this.Condition()
                    } else {
                        this.$router.push({
                            path: '/login'
                        });
                    }
                    //NProgress.done();
                });
            },
            //显示新增界面

            //编辑
            maskSubmit() {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {

                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let num = {
                                '1': this.editmask.maskWithout[0].list.join(','),
                                '2': this.editmask.maskWithout[1].list.join(','),
                                '3': this.editmask.maskWithout[2].list.join(','),
                                '4': this.editmask.maskWithout[3].list.join(','),
                                '5': this.editmask.maskWithout[4].list.join(','),
                                '6': this.editmask.maskWithout[5].list.join(','),
                                '7': this.editmask.maskWithout[6].list.join(',')
                            };
                            this.editmask.maskWithout = num;
                            console.log(this.editmask)
                            //NProgress.start();
                            let para = Object.assign({}, this.editmask);
                            console.log(para)
                            alarm_trigger_put_mask(para).then((res) => {
                                this.begCode(res.code,res.message);

                                    this.editLoading = false;
                                if (res.code == 0) {
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.editmask = {
                                        alarmTriggerId: '',
                                        maskStartTime: '',
                                        maskEndTime: '',
                                        maskWithout: [{
                                                name: '星期一',
                                                list: ['1']
                                            },
                                            {
                                                name: '星期二',
                                                list: []
                                            }, {
                                                name: '星期三',
                                                list: []
                                            }, {
                                                name: '星期四',
                                                list: []
                                            }, {
                                                name: '星期五',
                                                list: []
                                            }, {
                                                name: '星期六',
                                                list: []
                                            }, {
                                                name: '星期日',
                                                list: []
                                            },
                                        ]
                                    }
                                    this.$refs['editForm'].resetFields();
                                    this.maskFormVisible = false;
                                    this.getUsers();
                                }
                            });
                        });
                    }
                });
            },
            editSubmit: function () {
                console.log(this.alarmUserList)

                this.$refs.editForms.validate((valid) => {
                    if (valid) {

                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editForm.alarmTriggerGroupList = [];
                            // for (let i in this.alarmUserLists) {
                            //     this.editForm.alarmTriggerGroupList.push({
                            //         "type": 2,
                            //         "alarmTypeValue": this.alarmUserLists[i]
                            //     });
                            // }
                            // for (let i in this.editForm.alarmUserList) {
                            //     this.editForm.alarmTriggerGroupList.push({
                            //         "type": 1,
                            //         "alarmTypeValue": this.alarmUserList[i]
                            //     });
                            // }
                            for (let i in this.userlist) {
                                for (let j in this.alarmUserList) {
                                    if (this.alarmUserList[j] == i) {
                                        if (this.userlist[i].type == 1) {
                                            this.editForm.alarmTriggerGroupList.push({
                                                "type": 1,
                                                "alarmTypeValue": this.userlist[i].sid
                                            });
                                        } else {
                                            this.editForm.alarmTriggerGroupList.push({
                                                "type": 2,
                                                "alarmTypeValue": this.userlist[i].sid
                                            });
                                        }

                                        console.log(this.editForm.alarmTriggerGroupList)
                                    }
                                }
                            }
                            this.editLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);

                            alarm_trigger_put(para).then((res) => {
                                 this.begCode(res.code,res.message);

                                if (res.code == 0) {
                                    this.editLoading = false;
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();
                                }
                            });
                        });
                    }
                });
            },
            //新增

            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
              
                var ids = this.sels.map(item => item.alarmTriggerId).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        idList: ids.split(',')
                    };
                    alarm_trigger_delete(para).then((res) => {
                         this.begCode(res.code,res.message);
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            if(sessionStorage.getItem('facility_alarmTriggerId')){
                this.filters.deviceTypeId='';
            }
            this.menubt=localStorage.getItem('menubt');
            let para = {
                pageNo: 1,
                pageSize: 1000
            };
            let para1 = {
                name: 'triggerCondition',
                pageSize: 999,
                pageNo: 1,
            }
         
                //NProgress.start();
              
            // let start1 = new Date();
            // let start2 = new Date();
            // start1.setTime(start1.getTime() - 3600 * 1000 * 1 * 1);
            // start2.setTime(start2.getTime());

            // this.value4 = [this.getdata(start1), this.getdata(start2)];
            // this.editmask.maskStartTime = this.getdata(start1);
            // this.editmask.maskEndTime = this.getdata(start2);
            
            device_type_query(para).then((res) => {
                     this.begCode(res.code,res.message);

                    this.addLoading = false;
                    if (res.code == 0) {
                        this.typelist = res.data.list;
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'warning'
                        });
                    }

                });
            dict_query(para1).then((res) => {
                 this.begCode(res.code,res.message);
                if (res.code == 0) {
                    this.addLoading = false;

                    this.unitlist = res.data.list;


                }

            });
            let para2 = {
                name: 'alarmLevel',
                pageSize: 999,
                pageNo: 1,
            }
            dict_query(para2).then((res) => {
                 this.begCode(res.code,res.message);
                if (res.code == 0) {
                    this.addLoading = false;

                    this.alaem_grade = res.data.list;


                }

            });
            alarm_type_query(para).then((res) => {
                 this.begCode(res.code,res.message);
                if (res.code == 0) {
                    //NProgress.done();

                    this.alaem_type = res.data.list;

                }

            });

            device_data_recipe_query(para).then((res) => {
                if (res.code == 0) {
                    //NProgress.done();
                    this.deviceDataRecipe = res.data.list;

                }

            });
            let para3 = {
                deviceDataRecipeBodyId: this.filters.deviceDataRecipeBodyId,
            }
            device_data_recipe_list_body(para3).then((res) => {
                if(res.code == 0){
                    this.deviceDataRecipeBody = res.data.list
                }
            })
            this.getUsers();

        },
        destroyed(){
            sessionStorage.removeItem('triggerstype')
            sessionStorage.removeItem('deviceDataRecipeBodyId')
            sessionStorage.removeItem('deviceDataRecipeId')
        }
    }
</script>

<style >
.triggers-checkbox .el-checkbox{
    width: 10%;
    margin-left: 30px;
}
</style>